<?php
// +----------------------------------------------------------------------
// | Longbing [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright Chengdu longbing Technology Co., Ltd.
// +----------------------------------------------------------------------
// | Website http://longbing.org/
// +----------------------------------------------------------------------
// | Sales manager: +86-13558882532 / +86-13330887474
// | Technical support: +86-15680635005
// | After-sale service: +86-17361005938
// +----------------------------------------------------------------------

declare(strict_types=1);

namespace app\im\service;


use app\Common\service\LongbingUserService;
use app\im\model\ImChat;
use app\im\model\ImMessage;
use app\im\model\ImMessageFriend;
use longbingcore\tools\LongbingDefault;

class ImMessageFriendService
{


    /**
     * @param $uniacid
     * @param $userId
     * @param int $page
     * @param int $page_count
     * @功能说明:获得用户的好友列表
     * @author jingshuixian
     * @DataTime: 2020/1/16 14:51
     */
    public static function getFriendList($uniacid ,  $userId ,$page_count = 10 ){

        $imMessageFriend = new ImMessageFriend() ;

        $message_model   = new ImMessage();

        $where[] = [ 'user_id' , '=' , $userId  ];

        $friendList = $imMessageFriend->where($where)->order('is_read desc , update_time desc' )->paginate($page_count);
        foreach ($friendList as $key => &$friend ){

            $friendId = $friend['friend_id'] ;

            $customer = longbingGetUser($friendId , $uniacid );

            //判断客户是否是员工
            if(isset($customer['is_staff']) && !empty($customer['is_staff']))
            {
                $customer_info = longbingGetUserInfo($friendId , $uniacid );
                if(isset($customer_info['is_staff']) && !empty($customer_info['is_staff']))
                {
                    if(!empty($customer_info['avatar'])) {
                        $customer_info = transImagesOne($customer_info ,['avatar'] , $uniacid );
                    }
                    //是员工 就用员工头像 By.jingshuixian
                    if(!empty($customer_info['avatar'])) $customer['avatarUrl'] = $customer_info['avatar'];

                    $customer['nickName'] = empty($customer_info['name']) ?  $customer['nickName'] : $customer_info['name'];
                }
            }

            //没有头像就给一个默认头像
            $customer['avatarUrl'] = empty($customer['avatarUrl']) ?  LongbingDefault::$avatarImgUrl  : $customer['avatarUrl'];

            $friend['customer'] = $customer ;

            $friend['target_id'] = $friendId ;

            $friend['not_read_message_count'] = self::notReadCount($friend) ;

            $last_msg = self::getLastMsg($friend);
            //兼容老数据格式
            $friend['lastmessage'] = [

                'message_type' => !empty($last_msg)?$last_msg['message_type']:'text',

                'content'      => !empty($last_msg)?$last_msg['content']:'',

                'is_show'      => !empty($last_msg)?$last_msg['is_show']:1,

                'is_self'      => !empty($last_msg)&&$last_msg['user_id'] == $friend['user_id']?1:0

            ];

            $friend['time'] = date('Y-m-d H:i:s', $friend['update_time']);

        }

        return empty($friendList) ? [] : $friendList->toArray() ;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-27 16:10
     * @功能说明:后去最后一条消息(除开自己删除的)
     *
     *
     */
    public static function getLastMsg($friend){

        $message_model   = new ImMessage();
        //自己接收的
        $dis = [

            'user_id'   => $friend['friend_id'],

            'target_id' => $friend['user_id']
        ];

        $where = [];
        //自己发送的
        $where[] = ['user_id','=',$friend['user_id']];

        $where[] = ['target_id','=',$friend['target_id']];
        //要除开删除的
        $where[] = ['is_show','<>',2];

//        $where[] = ['target_is_show','<>',2];

        $last_msg = $message_model->where($dis)->where('target_is_show','<>',2)->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->order('create_time desc')->find();


        return !empty($last_msg)?$last_msg->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-27 16:38
     * @功能说明:未读消息读数量
     */
    public static function notReadCount($friend){

        $message_model   = new ImMessage();
        //自己接收的
        $dis = [

            'user_id'   => $friend['friend_id'],

            'target_id' => $friend['user_id'],

            'status'    => 1,

            'target_is_show' => 1

        ];

        $count = $message_model->where($dis)->count();

        return $count;
    }

    /**
     * @param $uniacid
     * @param $userId
     * @功能说明:老数据转移到新数据上
     * @author jingshuixian
     * @DataTime: 2020/1/16 14:52
     */
    public static function initOldFriendList($uniacid ,  $userId){
        $imMessageFriend = new ImMessageFriend() ;

        $where[] = ['uniacid' , '=' , $uniacid  ] ;
        $where[] = ['user_id' , '=' , $userId  ] ;
        $friendCount = $imMessageFriend->where($where)->count();

        if(! $friendCount){  //没有好友就用message数据导入好友列表
            $imMessage = new ImMessage() ;


            $whereIm[] = ['uniacid' , '=' , $uniacid ] ;
            $whereIm[] = ['status' ,'in' , [ 1,2] ] ;

            $whereOr[] = ['user_id' ,'=' ,$userId ] ;
            $whereOr[] = ['target_id' ,'=' ,$userId ] ;

            $chat_ids = $imMessage->where($whereIm)->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })->distinct(true)->field('chat_id')->select();

            $friendData = [] ;
            foreach ($chat_ids as $key => $item) {

                if ($item) {

                    $chat_id = $item['chat_id'];
                    $message = $imMessage->where([['uniacid', '=', $uniacid], ['chat_id', '=', intval($chat_id)], ['status', 'in', [1,2] ]])->where(function ($query) use ($whereOr) {
                        $query->whereOr($whereOr);
                    })->order('id desc')->find();

                    //这里代码和  updateFriendByMessage 里的代码,大部分是重复的,只是一个批量插入和一个此插入
                    if ($message) {

                        $friendId = $message['user_id'] != $userId ? $message['user_id'] : $message['target_id'];
                        //判断用户是否存在
                        if( !LongbingUserService::isUser($uniacid , $friendId) ) continue ;

                        $friendItem['user_id'] = $userId;

                        $friendItem['friend_id'] = $friendId;

                        $friendItem['uniacid'] = $uniacid;
                        //获取最后一条消息内容
                        $whereOr   = [];

                        $whereOr[] = ['user_id', '=', $userId];

                        $whereOr[] = ['target_id', '=', $userId];

                        $friendItem['message_type'] = $message['message_type'];

                        $friendItem['lastmessage']  = in_array(  $message['message_type']  , ['image'  , 'picture' ])  ? '[图片]' :$message['content'];

                        $friendItem['create_time']  = $message['create_time'];

                        $friendItem['update_time']  = $message['update_time'];

                        $friendItem['is_show']      = $message['is_show'];

                        $notReadMessageCount = $imMessage->where([
                            ['uniacid', '=', $uniacid],
                            ['user_id', '=', $friendId],
                            ['target_id', '=', $userId],
                            ['status', '=', 1]
                        ])->count();

                        $friendItem['not_read_message_count'] = $notReadMessageCount;

                        $friendItem['is_read'] = $notReadMessageCount ?  1 :  0 ;

                        $friendData[] = $friendItem;

                    }

                }
            }

            $inserCount = $imMessageFriend->insertAll($friendData);

            return  $inserCount;

        }


        return  false ;

    }

    /**
     * @author jingshuixian
     * @DataTime: 2020/1/16 15:03
     * @功能说明:根据消息数据更新好友信息
     */
    public static function updateFriendByMessage( ImMessage $message ){

        if ($message) {

            $userId = $message['user_id'] ;
            $friendId = $message['target_id'] ;
            $uniacid = $message['uniacid'] ;

            self::updateFriendByUserIdAndFriend($uniacid , $userId , $friendId ) ;
            self::updateFriendByUserIdAndFriend($uniacid , $friendId , $userId ) ;


        }

        return false ;

    }

    /**
     * @param ImMessage $message
     * @功能说明:更新用户好友的关系和未读数据信息
     * @author jingshuixian
     * @DataTime: 2020/1/16 16:47
     */
    public static function updateFriendByUserIdAndFriend( $uniacid , $userId , $friendId){

        //判断用户是否存在
        if( !LongbingUserService::isUser($uniacid ,  $userId) && !LongbingUserService::isUser( $uniacid , $friendId) ) return false ;

        $imMessage = new ImMessage() ;
        $imMessageFriend = new ImMessageFriend() ;

            $friendItem['user_id'] = $userId;
            $friendItem['friend_id'] = $friendId;
            $friendItem['uniacid'] = $uniacid;

            //获取最后一条消息内容
            $message = ImMessageService::getLastMessage( $uniacid , $userId , $friendId ) ;
            if($message){

                $friendItem['message_type'] = $message['message_type'];
                $friendItem['lastmessage'] = in_array(  $message['message_type']  , ['image' ,'picture' ])  ? '[图片]' : $message['content'];
                $friendItem['create_time'] = $message['create_time'];
                $friendItem['update_time'] = $message['update_time'];

            }else{
                $friendItem['message_type'] = '';
                $friendItem['lastmessage'] = '';
                $friendItem['create_time'] = time();
                $friendItem['update_time'] = time();
            }

            //更新我的未读消息
            $notReadMessageCount = $imMessage->where([
                ['uniacid', '=', $uniacid],
                ['user_id', '=',$friendId  ],
                ['target_id', '=', $userId ],
                ['status', '=', 1]
            ])->count();

            $friendItem['not_read_message_count'] = $notReadMessageCount;

            $friendItem['is_read'] = $notReadMessageCount ?  1 :  0 ;

            //判断 消息发送人好友关系
            $oneFriend = self::getOneByUserIdAndFriendId($userId,$friendId);
            if($oneFriend){
                $friendItem['id'] = $oneFriend['id'];

                $friendItem['create_time'] = $oneFriend['create_time'];

                return $imMessageFriend->update( $friendItem );
            }else{
                return  $imMessageFriend->insert( $friendItem );
            }



    }

    /**
     * @param $userId
     * @param $friendId
     * @功能说明:判断是否是好友关系
     * @author jingshuixian
     * @DataTime: 2020/1/16 15:12
     */
    public static function isFriend($userId , $friendId){

        $imMessageFriend = new ImMessageFriend() ;
        $where[] = ['user_id' ,'=' ,$userId ] ;
        $where[] = ['friend_id' ,'=' ,$friendId ] ;

        $count  = $imMessageFriend->where($where)->count();

        return $count ? true : false;
    }

    /**
     * @param $userId
     * @param $friendId
     * @功能说明:更新用户ID和朋友ID获取好友关系数据
     * @author jingshuixian
     * @DataTime: 2020/1/16 15:14
     */
    public static function getOneByUserIdAndFriendId($userId , $friendId){

        $imMessageFriend = new ImMessageFriend() ;
        $where[] = ['user_id' ,'=' ,$userId ] ;
        $where[] = ['friend_id' ,'=' ,$friendId ] ;

        return  $imMessageFriend->where($where)->find() ;
    }


    /**
     * @param $uniacid
     * @param $userId
     * @param $friendId
     * @功能说明:处理好友的已读情况
     * @author jingshuixian
     * @DataTime: 2020/1/16 17:23
     */
    public static function readMessage($uniacid  , $userId , $friendId){
        $imMessageFriend = new ImMessageFriend() ;
        $count = $imMessageFriend->where([  ['uniacid' , '=', $uniacid ]  ,  ['user_id' , '=' ,$userId  ]  , ['friend_id' , '=' , $friendId  ] ])->update([ 'is_read' => 0 , 'not_read_message_count' => 0 ]) ;

        return $count;
    }

}